package org.ricks.net.action.context.session;

import org.ricks.net.action.parser.ProtocolParser;
import org.ricks.net.action.rpc.RpcClient;
import org.ricks.net.action.rpc.RpcSessionManager;
import org.ricks.net.transport.AioSession;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

// TCP 会话适配器
public class TcpSessionAdapter extends Session {

    private final AioSession session;

    private final ProtocolParser parser;

    public TcpSessionAdapter(AioSession session,  ProtocolParser parser) {
        this.session = session;
        this.parser = parser;
    }

    @Override
    public void writeBinary(byte[] data) {
        if(session.isInvalid()) return;
        try {
            ByteBuffer buffer = ByteBuffer.allocate(4 + data.length);
            buffer.putInt(data.length);
            buffer.put(data);
            session.writeBuffer().write(buffer.array());  // 使用零拷贝写入
        } catch (Exception e) {
            throw new RuntimeException("写入失败", e);
        } finally {
            session.writeBuffer().flush();
        }
    }

    // 新增统一调用方法
    public <R> CompletableFuture<R> invoke(short cmd, Object body, Class<R> resultType) {
        RpcClient rpcClient = RpcSessionManager.getOrCreateClient(session, parser);
        return rpcClient.invoke(cmd, body, resultType);
    }

    // 新增带超时的调用
    public <R> CompletableFuture<R> invoke(short cmd, Object body, Class<R> resultType, long timeout, TimeUnit unit) {
        RpcClient rpcClient = RpcSessionManager.getOrCreateClient(session, parser);
        return rpcClient.invoke(cmd, body, resultType, timeout, unit);
    }

    @Override
    public void writeText(String text) {
        writeBinary(text.getBytes(StandardCharsets.UTF_8)); // TCP 统一转二进制
    }

    @Override
    public void close() {
        session.close();
    }

    public ProtocolParser getParser() {
        return parser;
    }
}

